package com.zhugang.week13.linkedlist;

/**
 * @program algorithms
 * @description: reverseGroup2
 * @author: chanzhugang
 * @create: 2022/10/28 12:50
 */
public class ReverseGroup2 {

    /**
     * 25 k个一组翻转链表
     *
     * @param head
     * @param k
     * @return
     */
    public ListNode reverseGroup(ListNode head, int k) {
        // 画图好理解：
        // 一般都定义一个结果链表：dummyHead + tail, 每k个翻转一次(头插法)，定义好插入后的位置
        ListNode dummyHead = new ListNode();
        ListNode tail = dummyHead;

        ListNode p = head;
        while (p != null) {
            int count = 0;
            ListNode q = p;
            while (q != null) {
                count++;
                if (count == k) {
                    break;
                }
                q = q.next;
            }
            // 找到要翻转的q节点
            if (q == null) {
                // 节点个数不够k个
                tail.next = p;
                return dummyHead.next;
            } else {
                ListNode tempNext = q.next;
                // 翻转
                ListNode[] nodes = reverse(p, q);
                tail.next = nodes[0];
                tail = nodes[1];
                p = tempNext;
            }
        }
        return dummyHead.next;
    }

    private ListNode[] reverse(ListNode head, ListNode tail) {
        // 翻转
        ListNode newHead = null;
        ListNode p = head;
        while (p != tail) {
            // 头插法
            ListNode tempNext = p.next;
            p.next = newHead;
            newHead = p;
            p = tempNext;
        }
        tail.next = newHead;
        // 可以不用这一步
        newHead = tail;
        return new ListNode[]{tail, head};
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}